package com.pixpark.GPUPixelApp

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.util.Log
import com.blankj.utilcode.util.PathUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

/**二次采样
 * Created by Administrator on 2016/6/16.
 */
object BitmapUtils {
    private const val MAX_SIZE = 1000
    private val TAG = "BitmapUtils"

    fun getDirName(Context: Context?): String? {
//        return "/" + Context.getResources().getString(R.string.app_name);
        return "/" + "GPUPixelApp"
    }

    fun startActionCrop(bitmap: Bitmap): Bitmap {
        var width = bitmap.width.toDouble()
        var height = bitmap.height.toDouble()
        if (width > height) {
            if (width > MAX_SIZE) {
                height = MAX_SIZE / width * height
                width = MAX_SIZE.toDouble()
            }
        } else {
            if (height > MAX_SIZE) {
                width = MAX_SIZE / height * width
                height = MAX_SIZE.toDouble()
            }
        }
        return Bitmap.createScaledBitmap(bitmap, width.toInt(), height.toInt(), true)
    }

    fun startActionCrop(bitmap: Bitmap, maxSize: Int): Bitmap {
        var width = bitmap.width.toDouble()
        var height = bitmap.height.toDouble()
        if (width > height) {
            if (width > maxSize) {
                height = maxSize / width * height
                width = maxSize.toDouble()
            }
        } else {
            if (height > maxSize) {
                width = maxSize / height * width
                height = maxSize.toDouble()
            }
        }
        return Bitmap.createScaledBitmap(bitmap, width.toInt(), height.toInt(), true)
    }

    fun bitmap2byteArray(bitmap: Bitmap): ByteArray {
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
        return byteArrayOutputStream.toByteArray()
    }

    fun saveBitmapToFile(filePath: String?, mBitmap: Bitmap): String? {
        val f = File(filePath)
        if (f.exists()) {
            f.delete()
        }
        try {
            f.createNewFile()
        } catch (e: IOException) {
            Log.d(TAG, "在保存图片时出错：$e")
            return null
        }
        var fOut: FileOutputStream? = null
        fOut = try {
            FileOutputStream(f)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut)
        return try {
            fOut?.flush()
            fOut?.close()
            f.absolutePath
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 向本地SD卡写网络图片
     *
     * @param bitmap
     */
    fun saveBitmap(context: Context?, fileName: String?, bitmap: Bitmap):String {
        try {
            // 创建文件流，指向该路径，文件名叫做fileName

            val file = File(PathUtils.getInternalAppCachePath() +  getDirName(context), fileName)
            // file其实是图片，它的父级File是文件夹，判断一下文件夹是否存在，如果不存在，创建文件夹
            val fileParent = file.parentFile
            if (!fileParent.exists()) {
                // 文件夹不存在
                fileParent.mkdirs() // 创建文件夹
            }
            // 将图片保存到本地
            bitmap.compress(
                Bitmap.CompressFormat.JPEG, 100,
                FileOutputStream(file)
            )
            return file.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }






    ////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////


    /**
     * 图片的缩放方法
     *
     * @param orgBitmap ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    fun getZoomImage(
        orgBitmap: Bitmap?,
        newWidth: Double,
        newHeight: Double
    ): Bitmap? {
        if (null == orgBitmap) {
            return null
        }
        if (orgBitmap.isRecycled) {
            return null
        }
        if (newWidth <= 0 || newHeight <= 0) {
            return null
        }

        // 获取图片的宽和高
        val width = orgBitmap.width.toFloat()
        val height = orgBitmap.height.toFloat()
        // 创建操作图片的matrix对象
        val matrix = Matrix()
        // 计算宽高缩放率
        val scaleWidth = newWidth.toFloat() / width
        val scaleHeight = newHeight.toFloat() / height
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight)
        return Bitmap.createBitmap(orgBitmap, 0, 0, width.toInt(), height.toInt(), matrix, true)
    }

    /**
     * bitmap转换成byte数组
     *
     * @param bitmap
     * @param needRecycle
     * @return
     */
    fun bitmapToByteArray(bitmap: Bitmap?, needRecycle: Boolean): ByteArray? {
        if (null == bitmap) {
            return null
        }
        if (bitmap.isRecycled) {
            return null
        }
        val output = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
        if (needRecycle) {
            bitmap.recycle()
        }
        val result = output.toByteArray()
        try {
            output.close()
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        }
        return result
    }
}